/******************************************************************************
*    Copyright (C), 2022 by D2X studio. All rights reserved.                  *
*                                                                             *
*    @file:      socket_client.c
*    @owner:     zhengjian.xie@gmail.com                                      *
*    @desc:                                                                   *
*    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +    *
* history:                                                                    *
*  <author>      <time>      <version>              <description>             *
*  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  *
*  |  Xzj |  20220423[13:56] | 1.0.0 |                  build              |  *
*  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  *
******************************************************************************/
#include "includes.h"
#include "sys/types.h"
#include "sys/socket.h"
#include <arpa/inet.h>

/** socket client data define */
static stEvent __sock_client_evt__ = { -1, no, nil };

void sock_client_callback(void* pVoid) {
    int ret;
    char buf[128] = { 0 };

    if ( __sock_client_evt__.fd > 0 ) {
        ret = read(__sock_client_evt__.fd, buf, sizeof(buf));
        printf("CLI: %s\n", buf);
    }
}

/** sock_client_init */
void sock_client_init(void) {
    struct sockaddr_in cli_addr = { 0 };

    __sock_client_evt__.doEvent = sock_client_callback;

    // (1) create socket
    __sock_client_evt__.fd = socket(AF_INET, SOCK_STREAM, 0);
    printf("CLI: socket: %d\n", __sock_client_evt__.fd);

    // (2) connect
    cli_addr.sin_family = AF_INET;
    cli_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    cli_addr.sin_port = htons(8080);
    connect(__sock_client_evt__.fd, (struct sockaddr *)&cli_addr, sizeof(cli_addr));

    // (3) event monitor
    app_event_add(&__sock_client_evt__);
}

/** sock_client_deinit */
void sock_client_deinit(void) {
    app_event_del(&__sock_client_evt__);
}

void sock_client_sendstr(const char* str) {
    if ( __sock_client_evt__.fd > 0 ) {
        write(__sock_client_evt__.fd, str, strlen(str) + 1);
    }
}
